package com.reisen;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Readxls {


    /**
     * 读取文档
     * @param fileName
     */
    public static void readFile(String fileName){
//        String fileName = "xxxx.xlsx";

        try {
            //创建工作簿对象
            XSSFWorkbook  xssfWorkbook = new XSSFWorkbook(new FileInputStream(fileName));
            //获取工作簿下sheet的个数
            int sheetNum = xssfWorkbook.getNumberOfSheets();
            System.out.println("该excel文件中总共有："+sheetNum+"个sheet");
            //遍历工作簿中的所有数据

            for(int i = 0;i<sheetNum;i++) {
                //读取第i个工作表
                System.out.println("读取第"+(i+1)+"个sheet");
                XSSFSheet sheet = xssfWorkbook.getSheetAt(i);
                //获取最后一行的num，即总行数。此处从0开始
                int maxRow = sheet.getLastRowNum();
                for (int row = 0; row <= maxRow; row++) {
                    //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
                    XSSFRow xssfRow = sheet.getRow(row);
                    if (xssfRow == null) continue;
                    int maxRol = xssfRow.getLastCellNum();
                     System.out.println("--------第" + (row+1) + "行的数据如下--------");
                    for (int rol = 0; rol < maxRol; rol++){
                        System.out.print(sheet.getRow(row).getCell(rol) + "  ");
                    }
                    System.out.println();
                }
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     *  输出文档
     */
    public static void writeFile(){

        try (//创建工作薄对象
             SXSSFWorkbook workbook = new SXSSFWorkbook()) {
            //创建工作表对象
            SXSSFSheet sheet = workbook.createSheet();
            //创建工作表的行

            workbook.setSheetName(0,"sheet");//设置sheet的Name

            //文档输出
            FileOutputStream out = new FileOutputStream("xxxx" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString() +".xlsx");
            workbook.write(out);
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {

        readFile("xxx.xlsx");

    }
    
}
